package edu.pxxy.zxl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class FoodDaoApi {
    private MyDBOpenHelper helper;
    public FoodDaoApi(Context context) {
        helper = new MyDBOpenHelper(context);
    }
    public long add(Food food) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("foodname", food.getFoodName());
        values.put("foodprice", food.getFoodPrice());
        values.put("count", food.getCount());
        long result = db.insert("food", null, values);
        db.close();
        return result;
    }
    public int delete(Food food) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int result = db.delete("food", "foodname = ?", new String[] {food.getFoodName()});
        db.close();
        return result;
    }
    public int update(Food food) {
        SQLiteDatabase db = helper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("count",food.getCount());
        int result = db.update("food", values, "foodname=?", new String[] {food.getFoodName()});
        db.close();
        return result;
    }
    //单个查询
    public boolean find(Food food) {
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.query("food", null, "foodname = ?", new String[]{food.getFoodName()}, null, null, null);
        boolean result = cursor.moveToNext();
        db.close();
        return result;
    }
    //查询所有
    public List<Food> FindAllFood() {
        SQLiteDatabase db = helper.getWritableDatabase();

        Cursor cursor = db.query("food", null, null, null, null, null,null);
        List<Food> foods = new ArrayList<Food>();
        Food food = null;
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            String name = cursor.getString(cursor.getColumnIndex("foodname"));
            Float foodprice = cursor.getFloat(cursor.getColumnIndex("foodprice"));
            int count = cursor.getInt(cursor.getColumnIndex("count"));
            food = new Food(id, name, foodprice,count);
            foods.add(food);
        }

        db.close();
        return foods;
    }
}
